<template>
  <Container class="manage-list">
    <div slot="header" class="container-header large">
      <Form class="search">
        <Row>
          <i-col span="11">
            <FormItem label="商品编码">
              <Input v-model.trim="list.form.code" placeholder="商品编码" :maxlength="20" @on-enter="onSearchBtnClick(1)" />
            </FormItem>
            <FormItem label="商品名称">
              <Input v-model.trim="list.form.keyword" placeholder="商品名称，品牌，分类，子标题" :maxlength="100" @on-enter="onSearchBtnClick(1)" />
            </FormItem>
          </i-col>
          <i-col span="11">
            <FormItem label="店铺类目">
              <ShopSelect v-model="list.form.ownerCategoryId" @input="onSearchBtnClick(1)" />
            </FormItem>
            <FormItem label="商品品牌" placeholder="商品品牌">
              <Select v-model="list.form.brandIdList" filterable clearable multiple placeholder="请选择品牌" @on-open-change="onChangeOpen" @on-change="onSearchBtnClick">
                <Option
                  v-for="item in brandList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value.toString()"
                />
              </Select>
            </FormItem>
          </i-col>
          <i-col class-name="search" span="2">
            <Button class="btn-search large" type="primary" icon="ios-search" @click="onSearchBtnClick" />
          </i-col>
        </Row>
      </Form>
    </div>
    <Tabs v-model="tab">
      <Button
        slot="extra"
        size="large"
        class="item"
        type="primary"
        icon="md-add"
        @click="onAddProduct"
      >新建商品</Button>
      <Button
        slot="extra"
        size="large"
        class="item"
        icon="md-sync"
        @click="onSyncProduct"
      >
        一键同步
        <Poptip trigger="hover" content="可从盘古同步花纹模板" transfer>
          <Icon type="ios-help-circle" size="18" />
        </Poptip>
      </Button>
      <Dropdown slot="extra" class="mr" @on-click="onAllPut">
        <Button type="warning" size="large">
          批量上下架
          <Icon type="ios-arrow-down" />
        </Button>
        <DropdownMenu slot="list">
          <DropdownItem name="1">批量上架</DropdownItem>
          <DropdownItem name="2">批量下架</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button
        slot="extra"
        size="large"
        class="item"
        icon="ios-flag"
        @click="onBulkTag"
      >批量商品标签</Button>
      <Button
        slot="extra"
        size="large"
        class="item"
        icon="ios-flag"
        @click="onBulkServiceTag"
      >批量服务标签</Button>
      <Button
        slot="extra"
        size="large"
        class="item"
        type="primary"
        icon="ios-flag"
        @click="onBulkSlogan"
      >批量标语</Button>
      <export-btn 
        :param="exportParam" 
        url="/product/business/page_product_info_and_tags_export" 
        class="item" 
        slot="extra" 
        text="政策导出Excel"></export-btn>
      <TabPane label="商品管理" name="tab1">
        <homeTable
          ref="homeTable"
          :list="list"
          @getData="getData"
          @onPageSizeChange="onPageSizeChange"
          @onPageChange="onPageChange"
          @onSelectionChange="onSelectionChange"
        />
      </TabPane>
    </Tabs>
    <TagEditItem ref="tagEdit" :product-ids="productIds" @update="getData" />
    <ServiceTagEditItem ref="serviceTagEdit" :product-ids="productIds" @update="getData" />
    <SloganEditItem ref="sloganEdit" :product-ids="productIds" @update="getData" />
    <ErpEditItem ref="erpEdit" @update="getData" />
    <ProductCopyItem ref="linkCopy" />
    <QrCodeItem ref="qrcode" />
    <MaterielEditItem ref="materielEdit" @update="getData" />
    <FreightDialog ref="FreightDialog" :list="freightList" @complete="getData" />
  </Container>
</template>
<script>
let firstUpdate = true
import homeTable from '~/homeTable'
import QrCodeItem from '@/components/QrCodeItem'
// import CategorySelect from '@/components/CategorySelect'
// import BrandSelect from '@/components/BrandSelect'
import ShopSelect from '@/components/ShopSelect'
import ManageListData from './list/ManageListData'
import TagEditItem from './list/TagEditItem'
import ServiceTagEditItem from './list/ServiceTagEditItem'
import SloganEditItem from './list/SloganEditItem'
import ErpEditItem from './list/ErpEditItem'
import MaterielEditItem from './list/MaterielEditItem'
import ProductCopyItem from './list/ProductCopyItem'
import FreightDialog from './list/FreightDialog'
import { clearEmpty } from '@/util'
import { mapGetters } from 'vuex'
export default {
  name: 'product/manage/list',
  components: {
    TagEditItem,
    SloganEditItem,
    ProductCopyItem,
    ErpEditItem,
    MaterielEditItem,
    QrCodeItem,
    // CategorySelect,
    // BrandSelect,
    ShopSelect,
    homeTable,
    FreightDialog,
    ServiceTagEditItem
  },
  data () {
    return {
      tab: 'tab1',
      list: ManageListData,
      productIds: [],
      freightList: []
    }
  },
  computed: {
    ...mapGetters(['brandList'])
  },
  watch: {
    $route () {
      let page = ~~this.$route.query.currentPage
      let table = this.list
      if (table.currentPage !== page) {
        table.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage
      }
      this.getData()
    },
    'list.form.categoryId' (newName) {
      if (newName) {
        this.getData()
      } else {
        this.list.form.categoryId = null
        this.getData()
      }
    }
  },
  async mounted () {
    this.$store.dispatch('getBrandList', true)
    this.list.currentPage = ~~this.$route.query.currentPage || 1
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.$bus.$on('onEdit', this.onEdit)
    this.$bus.$on('onDelete', this.onDelete)
    this.$bus.$on('onSwitch', this.onSwitch)
    this.$bus.$on('onChangeData', ({ val, params, index, type }) => this.onChangeData(val, params, index, type))
    this.$bus.$on('onChangeTagName', ({ params, index }) => this.onChangeTagName(params, index))
    this.$bus.$on('onBlurData', ({ params }) => this.onBlurData(params))
    this.$bus.$on('onLookErp', ({ centerProductId }) => this.onLookErp(centerProductId))
    this.$bus.$on('onLookMateriel', ({ centerProductId }) => this.onLookMateriel(centerProductId))
    this.$bus.$on('changeState', ({ data, key }) => {
      //状态选择
      if (data.length > 0) {
        this.list.form.isShelf = data[0] == 1
      } else {
        this.list.form.isShelf = null
      }
      this.onSearchBtnClick()
    })
    this.$bus.$on('setFreightBatch', () => {
      const param = {
        isShelf: this.list.form.isShelf,
        code: this.list.form.code,
        ownerCategoryId: this.list.form.ownerCategoryId,
        brandIdList: this.list.form.brandIdList,
        keyword: this.list.form.keyword
      }
      this.$refs.FreightDialog.open(param)
    })
    this.$bus.$on('changeFreight', (data) => {
      this.updateFreight(data)
    })
    await this.getFreightList()
    this.getData() //获取table列表信息
  },
  destroyed () {
    this.$bus.$off()
  },
  beforeRouteEnter (to, from, next) {
    firstUpdate = false
    next(vm => {})
  },
  methods: {
    getFreightList () {
      return this.$jsonPost('/freight/setting/page/product').then(res => {
        this.freightList = res.map(item => {
          return {
            id: item.id,
            name: item.freightName
          }
        })
      })
    },
    updateFreight (param) {
      this.$jsonPost('/product/business/update/freight', param).then(res => {
        this.$Notice.success({
          title: '更改成功'
        })
      })
    },
    onChangeOpen () {
      firstUpdate = true
    },
    onSearchBtnClick (type) {
      if (firstUpdate || type === 1) {
        this.list.currentPage = 1
        this.getData()
      }
      firstUpdate = true
    },
    onAllPut (v) {
      let url = ''
      if (v === '1') { // 上架
        url = '/product/business/onShelvesBacth/'
      } else if (v === '2') { // 下架
        url = '/product/business/offShelvesBacth/'
      }
      if (!this.productIds.length) {
        this.$Notice.warning({
          title: '请先选择商品'
        })
        return
      }
      this.list.status = 'loading'
      this.$jsonPost(url, this.productIds).then(() => {
        this.$Notice.success({
          title: '成功'
        })
        this.list.status = 'pass'
        this.getData()
      }).catch(() => {
        this.list.status = 'pass'
      })
    },
    getData () {
      this.productIds = []
      this.list.status = 'loading'
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        isShelf: this.list.form.isShelf,
        code: this.list.form.code,
        ownerCategoryId: this.list.form.ownerCategoryId,
        brandIdList: this.list.form.brandIdList,
        keyword: this.list.form.keyword
      }
      param = clearEmpty(param)
      this.$jsonPost('/product/business/page_product_info_and_tags', param).then(data => {
        this.list.data = []
        this.list.totalItem = Number(data.total)
        this.list.data = (data.records || []).map(item => {
          return {
            id: item.productInfoDTO.id,
            categoryName: item.productInfoDTO.categoryName ? item.productInfoDTO.categoryName : null,
            title: item.productInfoDTO.title ? item.productInfoDTO.title : null,
            code: item.productInfoDTO.code ? item.productInfoDTO.code : null,
            unit: item.productInfoDTO.unit ? item.productInfoDTO.unit : null,
            isShelf: item.productInfoDTO.isShelf,
            brandName: item.productInfoDTO.brandName ? item.productInfoDTO.brandName : null,
            salePrice: item.productSkuDTO.salePrice || item.productSkuDTO.salePrice === 0 ? item.productSkuDTO.salePrice : null,
            oldSalePrice: item.productSkuDTO.salePrice || item.productSkuDTO.salePrice === 0 ? item.productSkuDTO.salePrice : null,
            marketPrice: item.productSkuDTO.marketPrice || item.productSkuDTO.marketPrice === 0 ? item.productSkuDTO.marketPrice : null,
            invoicePrice: item.productSkuDTO.invoicePrice || item.productSkuDTO.invoicePrice === 0 ? item.productSkuDTO.invoicePrice : null,
            oldInvoice: item.productSkuDTO.invoicePrice || item.productSkuDTO.invoicePrice === 0 ? item.productSkuDTO.invoicePrice : null,
            stock: item.productSkuDTO.stock || item.productSkuDTO.stock === 0 ? item.productSkuDTO.stock : null,
            oldStock: item.productSkuDTO.stock || item.productSkuDTO.stock === 0 ? item.productSkuDTO.stock : null,
            tagName: item.productIdTagNameDTO ? (item.productIdTagNameDTO.tagName.length > 20 ? item.productIdTagNameDTO.tagName.substring(0, 20) + '...' : item.productIdTagNameDTO.tagName) : '',
            oldTagName: item.productIdTagNameDTO ? item.productIdTagNameDTO.tagName : '',
            productType: item.productInfoDTO.productType,
            skuId: item.productSkuDTO.id,
            centerProductId: item.productInfoDTO.centerProductId,
            isShowAllTag: false, // 显示剩余的标签
            freightList: this.freightList,
            freightTemplateId: item.productInfoDTO.freightTemplateId,
            productServiceTagNames: item.productServiceTagNames || '' // 服务标签
          }
        })
        this.list.status = 'pass'
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    onChangeData (val, params, index, type) {
      params[type] = val
      this.list.data[index] = params
    },
    onChangeTagName (params, index) {
      params.isShowAllTag = !params.isShowAllTag
      if (params.oldTagName.length > 20) {
        if (params.isShowAllTag) {
          params.tagName = params.oldTagName
        } else {
          params.tagName = params.oldTagName.substring(0, 20) + '...'
        }
      }
      this.list[index] = params
    },
    onLookErp (centerProductId) {
      if (centerProductId) this.$refs.erpEdit.updateForm(centerProductId)
    },
    onLookMateriel (centerProductId) {
      if (centerProductId) this.$refs.materielEdit.updateForm(centerProductId)
    },
    onBlurData (params) {
      let param = {
        invoicePrice: params.invoicePrice,
        marketPrice: params.marketPrice,
        salePrice: params.salePrice,
        stock: params.stock,
        skuId: params.skuId
      }
      this.$jsonPost(`/product/product_sku/updateByProductId/${params.id}`, param).then(data => {
        this.$Notice.success({
          title: '修改成功'
        })
      })
    },
    onQrCode (item) {
      this.$refs.qrcode.openModal({ routerEnum: 'spu_detail', sourceEnum: 'default_source', text: `${item.sn}`, width: 300 })
    },
    onEdit (id) {
      this.$router.push({
        name: 'product/manage/edit/edit',
        query: {
          productId: id,
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
    },
    onSwitch (id, val, index) {
      let url = val ? '/product/business/onShelves/' : '/product/business/offShelves/'
      this.$ajaxPost(`${url}${id}`).then(data => {
        this.$Message.success('设置成功')
      }).catch(() => {
        this.$nextTick(() => {
          this.list.data[index].isShelf = !val
          let newData = JSON.parse(JSON.stringify(this.list.data))
          this.list.data = []
          setTimeout(() => {
            this.$set(this.list, 'data', newData)
          }, 10)
        })
      })
    },
    // copy链接
    onOpenCopy (row) {
      this.$nextTick(() => {
        this.$refs.linkCopy.openModal(row)
      })
    },
    onDelete (id, name) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除当前商品？',
        onOk: () => {
          let param = {
            productIds: id
          }
          this.$ajaxPost('/product/business/delete', param).then(data => {
            this.$Notice.success({
              title: '删除成功',
              desc: `<span class="font-red">${name}</span> 已被删除。`
            })
            this.getData()
          })
        }
      })
    },
    onAddProduct () {
      this.$router.push({
        name: 'product/manage/edit/edit',
        query: {
          flag: true
        }
      })
    },
    onSyncProduct () {
      if (!this.productIds.length) {
        this.$Notice.warning({
          title: '请先选择商品'
        })
        return
      }
      this.$Modal.confirm({
        title: '确定',
        content: '确定同步当前商品？',
        onOk: () => {
          let param = {
            productIds: this.productIds
          }
          this.$ajaxPost('/product/business/syncFigure', param).then(data => {
            this.$Notice.success({
              title: '同步成功'
            })
            this.$refs.homeTable.clearSelectAll()
          })
        }
      })
    },
    onSelectionChange (selection) {
      this.productIds = (selection || []).map(item => item.id)
    },
    onBulkTag () {
      if (!this.productIds.length) {
        this.$Message.warning('请先选择商品')
        return
      }
      this.$refs.tagEdit.getTagData()
    },
    onBulkServiceTag () {
      if (!this.productIds.length) {
        this.$Message.warning('请先选择商品')
        return
      }
      this.$refs.serviceTagEdit.getTagData()
    },
    onBulkSlogan () {
      if (!this.productIds.length) {
        this.$Message.warning('请先选择商品')
        return
      }
      this.$refs.sloganEdit.resetForm()
    },
    onPageChange (number) {
      this.list.currentPage = number
      this.$router.push({
        name: 'product/manage/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
    },
    onPageSizeChange (pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.$router.push({
        name: 'product/manage/list',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
    }
  },
  computed: {
    exportParam() {
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        isShelf: this.list.form.isShelf,
        code: this.list.form.code,
        ownerCategoryId: this.list.form.ownerCategoryId,
        brandIdList: this.list.form.brandIdList,
        keyword: this.list.form.keyword
      }
      param = clearEmpty(param)
      return param
    }
  }
}
</script>
